package TicketingSystem;

import connection.Conn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserService {
    private static final Logger LOGGER = Logger.getLogger(UserService.class.getName());

    // 用户登录
    public static int login(String username, String password, boolean isAdmin) {
        String sql;
        if (isAdmin) {
            sql = "SELECT * FROM Users WHERE Username = ? AND Password = ? AND UserStatus = '管理员'";
        } else {
            sql = "SELECT * FROM Users WHERE Username = ? AND Password = ?";
        }
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return -1;
            }
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt("UserID");
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行登录查询时出现 SQL 异常", e);
        }
        return -1;
    }

    // 用户注册
    public static boolean register(User user) {
        String sql = "INSERT INTO Users (Username, Password, ContactInfo, UserStatus) VALUES (?,?,?,?)";
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return false;
            }
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getContactInfo());
            pstmt.setString(4, user.getUserType());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行注册插入操作时出现 SQL 异常", e);
            return false;
        }
    }

    // 用户修改密码
    public static boolean changePassword(String username, String oldPassword, String newPassword) {
        try (Connection conn = Conn.getConn()) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return false;
            }
            // 先验证旧密码是否正确
            String checkSql = "SELECT * FROM Users WHERE Username =? AND Password =?";
            try (PreparedStatement checkPstmt = conn.prepareStatement(checkSql)) {
                checkPstmt.setString(1, username);
                checkPstmt.setString(2, oldPassword);
                try (ResultSet rs = checkPstmt.executeQuery()) {
                    if (!rs.next()) {
                        return false; // 旧密码不正确
                    }
                }
            }
            // 更新密码
            String updateSql = "UPDATE Users SET Password =? WHERE Username =?";
            try (PreparedStatement updatePstmt = conn.prepareStatement(updateSql)) {
                updatePstmt.setString(1, newPassword);
                updatePstmt.setString(2, username);
                int rows = updatePstmt.executeUpdate();
                return rows > 0;
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行密码修改操作时出现 SQL 异常", e);
            return false;
        }
    }

    // 获取用户信息
    public static User getUserInfo(int userID) {
        String sql = "SELECT * FROM Users WHERE UserID = ?";
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return null;
            }
            pstmt.setInt(1, userID);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User(rs.getString("Username"), rs.getString("Password"), rs.getString("ContactInfo"), rs.getString("UserStatus"));
                    user.setUserID(rs.getInt("UserID"));
                    return user;
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行获取用户信息查询时出现 SQL 异常", e);
        }
        return null;
    }

    // 更新用户信息
    public static boolean updateUserInfo(int userID, String password, String contactInfo, String userType) {
        String sql = "UPDATE Users SET ";
        StringBuilder setClause = new StringBuilder();
        java.util.List<Object> params = new ArrayList<>();
        if (password != null) {
            setClause.append("Password = ?, ");
            params.add(password);
        }
        if (contactInfo != null) {
            setClause.append("ContactInfo = ?, ");
            params.add(contactInfo);
        }
        if (userType != null) {
            setClause.append("UserStatus = ?, ");
            params.add(userType);
        }
        if (setClause.length() == 0) {
            return false;
        }
        sql += setClause.substring(0, setClause.length() - 2);
        sql += " WHERE UserID = ?";
        params.add(userID);

        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行更新用户信息操作时出现 SQL 异常", e);
            return false;
        }
    }

    // 获取所有用户信息
    public static List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM Users";
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return users;
            }
            while (rs.next()) {
                User user = new User(rs.getString("Username"), rs.getString("Password"), rs.getString("ContactInfo"), rs.getString("UserStatus"));
                user.setUserID(rs.getInt("UserID"));
                users.add(user);
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行获取所有用户信息查询时出现 SQL 异常", e);
        }
        return users;
    }

    // 根据关键字搜索用户信息
    public static List<User> searchUsers(String keyword) {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM Users WHERE Username LIKE ? OR ContactInfo LIKE ? OR UserStatus LIKE ?";
        try (Connection conn = Conn.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            if (conn == null) {
                LOGGER.severe("无法获取数据库连接");
                return users;
            }
            pstmt.setString(1, "%" + keyword + "%");
            pstmt.setString(2, "%" + keyword + "%");
            pstmt.setString(3, "%" + keyword + "%");
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    User user = new User(rs.getString("Username"), rs.getString("Password"), rs.getString("ContactInfo"), rs.getString("UserStatus"));
                    user.setUserID(rs.getInt("UserID"));
                    users.add(user);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "执行搜索用户信息查询时出现 SQL 异常", e);
        }
        return users;
    }
}